<?php
header('Content-type: text/html; charset=UTF-8');
error_reporting(E_ALL);ini_set('display_errors',1);

define('QINIU_DOMAIN', 'http://qn.touhaoshiwan.com/');
define('MYSQL_HOST', 'localhost');
define('MYSQL_USERNAME', 'root');
define('MYSQL_PASSWORD', 'Sem_1653');
define('MYSQL_DBNAME', 'testtoutiao');
/******************** pdo **********************************/
$dsn = "mysql:host=".MYSQL_HOST.";dbname=".MYSQL_DBNAME;
$dbh = new PDO($dsn, MYSQL_USERNAME, MYSQL_PASSWORD);
$dbh->query('set names utf8;');
/**********************/

$yyb_url = 'http://www.touhaoshiwan.com/pc/';  //安卓
$ios_url = 'http://www.touhaoshiwan.com/pc/';
$id = !empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
$remote_ip = getIP();
$curtime = time();
$device_type = 3;

#浏览器判断
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
if ( strpos($userAgent, 'micromessenger') != false || strpos($userAgent, 'qq') != false ) {
    $link = $yyb_url;
} else {
    $clientkeywords = array ('iphone', 'ipad', 'ipod' );
    if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", $userAgent)) {
        $link = $ios_url;
        $device_type = 2;
    } else {
        $link = $yyb_url;
    }
}

if(!empty($remote_ip) && $id > 0) {
    #确定该ID存在
    $sql = "SELECT * FROM click_stat where id={$id} limit 1";
    $result = $dbh->query($sql);
    $statinfo = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT);

    if(!empty($statinfo)) {
        #一小时内不重复统计
        $sql = "SELECT id FROM click_list WHERE remote_ip='{$remote_ip}' and stid={$id} and created_at>".($curtime-3600)." order by id desc limit 1";
        $result = $dbh->query($sql);
        $userinfo = $result->fetch();

        if(empty($userinfo)) {
            $sql = "UPDATE click_stat SET clk_num=clk_num+1 WHERE id={$id}";
            $dbh->exec($sql);
            $sql = "INSERT INTO click_list (remote_ip, stid, device_type, created_at) VALUES ('{$remote_ip}', {$id}, {$device_type}, {$curtime})";
            $dbh->exec($sql);
        }

        if(!empty($statinfo['third_url'])) {
            $link = $statinfo['third_url'];
        }
    }
}

header('Location: '. $link);


function getIP() {
    if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('HTTP_X_FORWARDED')) {
        $ip = getenv('HTTP_X_FORWARDED');
    } elseif (getenv('HTTP_FORWARDED_FOR')) {
        $ip = getenv('HTTP_FORWARDED_FOR');
    } elseif (getenv('HTTP_FORWARDED')) {
        $ip = getenv('HTTP_FORWARDED');
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
?>